import { Popconfirm } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { useState, PropsWithChildren } from 'react';

export interface IConfirmBtnProps {
    onConfirm: () => void|Promise<void>, onCancel?: () => void, title?: string
}
export function ConfirmBtn(props: PropsWithChildren<IConfirmBtnProps>) {
    let [ isLoading, setIsLoading ] = useState(false);
    function confirm() {
        let result = props.onConfirm();
        if(result !== undefined) {
            try {
                setIsLoading(true);
                result.then(() => setIsLoading(false));
            } catch (error) {
                setIsLoading(false);
                console.warn(error);
            }
        }
    }
    if(isLoading == false) {
        return (
            <Popconfirm 
            onConfirm={confirm} 
            onCancel={props.onCancel?props.onCancel: undefined} title={props.title?props.title: '确认删除？'}
            okText="确认"
            cancelText="取消"
            >
                {props.children}
            </Popconfirm>
        );
    }
    return <LoadingOutlined />
}